import { useMemo } from "react";
import { useProject } from "../../utils/project";
import { useSetUrlSearchParam, useUrlQueryParam } from "../../utils/url";

//项目列表搜索的参数 
export const useProjectsSearchParams = ()=>{
    const [param,setParam] = useUrlQueryParam(['name','personId']);

    return [
        useMemo(()=>({...param,personId:Number(param.personId) || undefined}),[param]),
        setParam        
    ] as const;
}

export const useProjectsQueryKey = ()=>{
    const [param] = useProjectsSearchParams();
    return ['projects',param];
}

export const useProjectModal = ()=>{
    const [{ projectCreate }, setProjectCreate] = useUrlQueryParam([
        "projectCreate",
    ]);
    const [{ editingProjectId }, setEditingProjectId] = useUrlQueryParam([
        "editingProjectId",
    ]);

    const setUrlParams = useSetUrlSearchParam();

    const { data: editingProject, isLoading } = useProject(
        Number(editingProjectId)
    );

    const open = () => {
        setProjectCreate({ projectCreate: true });
    }
    //给projectCreate false的话 关闭后url上还是会显示 
    //这样写因为顺序原因 创建项目和编辑项目有一种情况关不掉
    // const close = ()=>{
    //     setEditingProjectId({editingProjectId:undefined});
    //     setProjectCreate({projectCreate:undefined});
    // };
    const close = ()=>setUrlParams({projectCreate:'',editingProjectId:''});
    const startEdit = (id:number)=>setEditingProjectId({editingProjectId:id});

    return {
        projectModalOpen:projectCreate === 'true' || !!editingProjectId,
        open,
        close,
        startEdit,
        editingProject,
        isLoading
    }
}